<template>
  <div v-if="showInstallPrompt" class="pwa-install-prompt">
    <div class="install-content">
      <div class="install-icon">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 2L12 14M12 14L8 10M12 14L16 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          <path d="M3 17V19C3 20.1046 3.89543 21 5 21H19C20.1046 21 21 20.1046 21 19V17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </div>
      <div class="install-text">
        <h3>安装应用</h3>
        <p>将山河维护页面添加到主屏幕，获得更好的体验</p>
      </div>
      <div class="install-actions">
        <button @click="installPWA" class="install-btn">
          安装
        </button>
        <button @click="dismissPrompt" class="dismiss-btn">
          稍后
        </button>
      </div>
    </div>
    <button @click="dismissPrompt" class="close-btn">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </button>
  </div>
</template>

<script>
export default {
  name: 'PWAInstallPrompt',
  data() {
    return {
      showInstallPrompt: false,
      deferredPrompt: null,
      isIOS: false
    }
  },
  mounted() {
    this.checkInstallability()
    this.setupEventListeners()
  },
  methods: {
    checkInstallability() {
      // 检测是否为iOS设备
      this.isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)
      
      // 检查是否已经安装
      if (window.matchMedia('(display-mode: standalone)').matches) {
        return // 已经安装，不显示提示
      }
      
      // 检查是否已经被用户拒绝
      const dismissed = localStorage.getItem('pwa-install-dismissed')
      if (dismissed) {
        const dismissedTime = parseInt(dismissed)
        const daysSinceDismissed = (Date.now() - dismissedTime) / (1000 * 60 * 60 * 24)
        if (daysSinceDismissed < 7) {
          return // 7天内被拒绝过，不再显示
        }
      }
      
      // iOS设备显示手动安装提示
      if (this.isIOS) {
        setTimeout(() => {
          this.showInstallPrompt = true
        }, 3000) // 3秒后显示
      }
    },
    
    setupEventListeners() {
      // 监听beforeinstallprompt事件（非iOS设备）
      window.addEventListener('beforeinstallprompt', (e) => {
        e.preventDefault()
        this.deferredPrompt = e
        
        // 延迟显示安装提示
        setTimeout(() => {
          this.showInstallPrompt = true
        }, 3000)
      })
      
      // 监听安装完成事件
      window.addEventListener('appinstalled', () => {
        console.log('PWA was installed')
        this.showInstallPrompt = false
        this.deferredPrompt = null
      })
    },
    
    async installPWA() {
      if (this.isIOS) {
        // iOS设备显示手动安装说明
        this.showIOSInstallInstructions()
        return
      }
      
      if (!this.deferredPrompt) {
        return
      }
      
      try {
        // 显示安装提示
        this.deferredPrompt.prompt()
        
        // 等待用户响应
        const { outcome } = await this.deferredPrompt.userChoice
        
        if (outcome === 'accepted') {
          console.log('User accepted the install prompt')
        } else {
          console.log('User dismissed the install prompt')
        }
        
        this.deferredPrompt = null
        this.showInstallPrompt = false
        
      } catch (error) {
        console.error('Error during PWA installation:', error)
      }
    },
    
    showIOSInstallInstructions() {
      alert('要安装此应用：\n1. 点击分享按钮 📤\n2. 选择"添加到主屏幕"\n3. 点击"添加"')
      this.dismissPrompt()
    },
    
    dismissPrompt() {
      this.showInstallPrompt = false
      // 记录拒绝时间
      localStorage.setItem('pwa-install-dismissed', Date.now().toString())
    }
  }
}
</script>

<style scoped>
.pwa-install-prompt {
  position: fixed;
  bottom: 20px;
  left: 20px;
  right: 20px;
  background: rgba(15, 15, 35, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(99, 102, 241, 0.3);
  border-radius: 12px;
  padding: 16px;
  z-index: 1000;
  animation: slideUp 0.3s ease-out;
  max-width: 400px;
  margin: 0 auto;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.install-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.install-icon {
  color: #6366f1;
  flex-shrink: 0;
}

.install-text {
  flex: 1;
}

.install-text h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.install-text p {
  margin: 0;
  font-size: 14px;
  color: #a1a1aa;
  line-height: 1.4;
}

.install-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.install-btn {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.install-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
}

.dismiss-btn {
  background: transparent;
  color: #a1a1aa;
  border: 1px solid rgba(161, 161, 170, 0.3);
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.dismiss-btn:hover {
  color: #ffffff;
  border-color: rgba(255, 255, 255, 0.3);
}

.close-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  background: transparent;
  border: none;
  color: #a1a1aa;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.2s ease;
}

.close-btn:hover {
  color: #ffffff;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .pwa-install-prompt {
    left: 16px;
    right: 16px;
    bottom: 16px;
  }
  
  .install-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .install-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>